﻿using System;
using System.Reflection;
using System.Data.SqlClient;
using EasyMapping.Core;
using EasyMapping.Common;
using System.Data.Common;

namespace EasyMapping.Core
{
     class ReflectionManager
    {
         public static object GetColumnValue(PropertyInfo p, DbDataReader reader)
        {
            object[] arr = p.GetCustomAttributes(false);
            if (arr.Length >= 1)
            {
                foreach (var attribute in arr)
                {
                    PersistablePropertyAttribute temp = attribute as PersistablePropertyAttribute;
                    if (temp != null
                        && temp.ProcedureColumnName != null)
                    {
                        int index = reader.GetOrdinal(temp.ProcedureColumnName);
                        if (!reader.IsDBNull(index))
                        {
                            object value = reader.GetValue(index);
                            return value;
                        }
                        return null; 
                    }
                }
            }
            return null;
        }

        public static object GetObjectPropertyValue(Type type, string propertyName, object obj)
        {
            PropertyInfo property = type.GetProperty(propertyName);
            return property.GetValue(obj, null);
        }

        public static void SetPropertyValue(Type type, DbDataReader reader, ref object obj)
        {
            PropertyInfo[] properties = ReflectionCache.GetPropertyInfo(type);
            foreach (var p in properties)
            {
                object value = ReflectionManager.GetColumnValue(p, reader);
                if (value != null)
                {
                    p.SetValue(obj, value, null);
                }
            }
        }

        public static object GetInstance(Type type)
        {
            ConstructorInfo constructor = ReflectionCache.GetConstructorInfo(type);
            return constructor.Invoke(null);
        }
    }
}
